import ConfigParser
import threading, subprocess
import win32crypt, binascii

class RDPpword:
	def get_51_hash(self,pword_str):
		pwdHash = win32crypt.CryptProtectData(unicode(pword_str),u'psw',None,None,None,0)
		return str(binascii.hexlify(pwdHash)).upper()

class RDPconfig:
	def __init__(self):
		self.config = ConfigParser.RawConfigParser(allow_no_value=True)
		self.config.read("config.ini")
		self.onepass = self.config.get("general","onepass")
		if int(self.onepass) == 1: 
			self.onepass = True 
		else:
			self.onepass = False
		self.onepass_attr = {}
		if self.onepass:
			self.onepass_attr['domain'] = self.config.get("general","onepass_domain")
			self.onepass_attr['username'] = self.config.get("general","onepass_username")
			self.onepass_attr['password'] = self.config.get("general","onepass_password")
			self.config.set("general","onepass_password",self.define_password(self.onepass_attr['password']))
			with open("config.ini", 'wb') as conff:
				self.config.write(conff)
	def define_password(self,pword_str):
		if len(pword_str.strip()) > 300:
			return pword_str
		else:
			pwd = RDPpword()
			return pwd.get_51_hash(pword_str)
		
	def get_server_list(self):
		self.__init__()
		config = self.config
		server_names = config.get("servers","names")
		server_list = {}
		for name in server_names.split(','):
			server = {}
			name = name.strip()
			server['domain'] = config.get(name,'domain')
			server['username'] = config.get(name,'username')
			server['password'] = config.get(name,'password')
			if not self.onepass:
				server_list[name] = server
			else:
				server_list[name] = self.onepass_attr
		return server_list
	def set_server(self, servername, attr):
		self.__init__()
		config = self.config
		attr['password'] = self.define_password(attr['password'])
		server_names = config.get("servers","names")
		if not servername in server_names:
			config.remove_option("servers","names")
			server_names += ', ' + servername
			config.set("servers","names",server_names)
			config.add_section(servername)
		else:
			config.remove_section(servername)
			config.add_section(servername)
		config.set(servername,'domain',attr['domain'])
		config.set(servername,'username',attr['username'])
		config.set(servername,'password',attr['password'])
		with open("config.ini", 'wb') as conff:
			config.write(conff)
	def remove_server(self,servername):
		self.__init__()
		config = self.config
		server_names = config.get("servers","names").split(',')
		for i, server in enumerate(server_names): server_names[i] = server.strip() 
		if servername in server_names: server_names.remove(servername)
		s = ''
		for server in server_names: s += server+','
		server_names = s.strip(',')
		config.remove_option("servers","names")
		config.remove_section(servername)
		config.set("servers","names",server_names)
		with open("config.ini", 'wb') as conff:
			config.write(conff)

class RDPconfile:
	def create_con_file(self,server,attr):
		const_str = """screen mode id:i:1
		desktopwidth:i:1280
		desktopheight:i:1024
		session bpp:i:32
		winposstr:s:0,3,0,0,800,600
		compression:i:1
		keyboardhook:i:2
		audiocapturemode:i:0
		videoplaybackmode:i:1
		connection type:i:2
		displayconnectionbar:i:1
		disable wallpaper:i:1
		allow font smoothing:i:0
		allow desktop composition:i:0
		disable full window drag:i:1
		disable menu anims:i:1
		disable themes:i:0
		disable cursor setting:i:0
		bitmapcachepersistenable:i:1
		audiomode:i:0
		redirectprinters:i:1
		redirectcomports:i:0
		redirectsmartcards:i:1
		redirectclipboard:i:1
		redirectposdevices:i:0
		redirectdirectx:i:1
		autoreconnection enabled:i:1
		authentication level:i:0
		prompt for credentials:i:0
		negotiate security layer:i:1
		remoteapplicationmode:i:0
		alternate shell:s:
		shell working directory:s:
		gatewayhostname:s:
		gatewayusagemethod:i:4
		gatewaycredentialssource:i:4
		gatewayprofileusagemethod:i:0
		promptcredentialonce:i:1
		use redirection server name:i:0
		drivestoredirect:s:
		"""
		f = open(server + "_RDP.rdp",'w')
		f.write("full address:s:"+server+"\n")
		f.write("username:s:"+attr['username']+"\n")
		f.write("domain:s:"+attr['domain']+"\n")
		f.write("password 51:b:"+attr['password']+"\n")
		f.write(const_str)
		return f.name

class rdpThread(threading.Thread):
	confile = ""
	def run(self):
		subprocess.call(["mstsc.exe",self.confile])

class RDPthread():
	def __init__(self, confile):
		rdpT = rdpThread()
		rdpT.confile = confile
		rdpT.start()

class mainInterface():
	def __init__(self):
		self.RDPconfile = RDPconfile()
		self.RDPconfig = RDPconfig()
		self.server_list = self.RDPconfig.get_server_list()
	def createConn(self, servername, attr):
		connfile = self.RDPconfile.create_con_file(servername, attr)
		return connfile
	def startRDP(self, servername):
		if self.server_list[servername]:
			connfile = self.createConn(servername,self.server_list[servername])
			RDPthread(connfile)
	def startRDP_ALL(self):
		for servername in self.server_list.keys():
			connfile = self.createConn(servername,self.server_list[servername])
			RDPthread(connfile)
	def set_serverConfig(self,servername,attr):
		self.RDPconfig.set_server(servername,attr)
		self.server_list = self.RDPconfig.get_server_list()
	def remove_serverConfig(self,servername):
		self.RDPconfig.remove_server(servername)
		self.server_list = self.RDPconfig.get_server_list()